import {ScrollView, View, Text, Image} from '@tarojs/components';
import React, {Component} from 'react';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import moment from 'dayjs';
import actions from './actions';
import {store2Props} from './selectors';
import api from 'api';
import {AtCurtain} from 'taro-ui';
import 'taro-ui/dist/style/components/curtain.scss';
import bgImg from '@/assets/image/pointCheck/poincheck_bg.png';
import PrightImg from '@/assets/image/pointCheck/p_right.png';
import RrightImg from '@/assets/image/pointCheck/r_right.png';
import noticeImg from '@/assets/image/pointCheck/notice.png';
import btnImg from './img/btn.png';
import Tab from './components/tab';
import AdvModal from '@/pages/common/adv-modal/adv-modal';
import {fetchModal, handleUrl, setModalShow, pvUvStatics} from 'wmkit';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      refresherTriggered: false,
      isModalFlag: false,
      imgUrl: '',
      jumpPage: {},
    };
  }

  async componentWillMount() {
    if (__TARO_ENV !== 'h5') {
      Taro.showShareMenu({
        withShareTicket: true,
      });
    }
    this.updateModalStatus('');
  }

  componentDidMount() {
    this.props.actions.init();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  async updateModalStatus(id) {
    const res = await fetchModal('integralMall');
    let popupId = null;
    if (!id && res && res.length > 0) {
      popupId = res[0].popupId;
    } else {
      popupId = id;
    }
    const flagParams = await setModalShow(res, 'integralMall', popupId);
    this.setState(
      {
        isModalFlag: flagParams.showFlag,
        imgUrl: flagParams.imgUrl,
        jumpPage: (flagParams.jumpPage && JSON.parse(flagParams.jumpPage)) || '',
        nextPopupId: flagParams.nextPopupId,
      },
      () => {
        if (this.state.nextPopupId && !this.state.isModalFlag) {
          this.isGo(this.state.nextPopupId);
        }
      },
    );
  }
  async isGo(id) {
    await this.updateModalStatus(id);
  }
  handleClose() {
    this.setState({isModalFlag: false}, async () => {
      if (this.state.nextPopupId) {
        await this.updateModalStatus(this.state.nextPopupId);
      }
    });
  }

  _onScrollToLower = () => {
    let {
      main: {pageNum, totalPages},
      actions: {action},
    } = this.props;
    let num = pageNum + 1;
    if (num == totalPages) return;
    this.props.actions.action.commonChange('main.pageNum', num);
    this.props.actions.action.findPointsMall();
  };

  _onRefresherRefresh = () => {
    let {refresherTriggered} = this.state;
    if (refresherTriggered) return;
    this.setState({
      refresherTriggered: true,
    });
    this.props.actions.action.commonChange('main.pageNum', 0);
    this.props.actions.action.findPointsMall();
    setTimeout(() => {
      this.setState({
        refresherTriggered: false,
      });
    }, 2000);
  };

  async btnClick(giftType) {
    if (giftType == 1) {
      //跳转到我的优惠券
      Taro.redirectTo({
        url: '/pages/package-A/customer/my-coupon/index',
      });
    } else {
      //跳转到我的奖励
      Taro.redirectTo({
        url: '/pages/package-C/prizesRecord/index',
      });
    }
  }

  render() {
    let {refresherTriggered} = this.state;
    let {
      main: {
        pointsAvailable,
        pointsExpireDay,
        pointsExpireMonth,
        continuousDays,
        daysNumArr,
        showMode,
        successMessage,
        signFlag,
        giftType,
      },
      actions: {action},
    } = this.props;
    return (
      <ScrollView
        className="packageCPointsMall"
        onScrollToLower={this._onScrollToLower}
        refresherEnabled
        refresherTriggered={refresherTriggered}
        onRefresherPulling={this._onRefresherRefresh}
        scrollY
        enhanced
        scroll-with-animation
        id="pointsScroll"
      >
        <Image className="bg" mode="widthFix" src={bgImg} />
        <View></View>
        <View className="pageHeader">
          <View
            onClick={() => {
              Taro.navigateTo({
                url: '/pages/package-C/points-mall/record/index',
              });
            }}
          >
            <View>
              <Text className="points">{pointsAvailable}</Text>
            </View>
            <View className="row" style={{justifyContent: 'flex-start'}}>
              <Text className="my-points">我的积分</Text>
              <Image className="right" mode="widthFix" src={PrightImg} />
            </View>
          </View>
          <View className="header-right">
            <View
              className="list"
              style={{marginBottom: '12px'}}
              onClick={() => {
                Taro.navigateTo({
                  url: '/pages/package-C/points-mall/rule/index',
                });
              }}
            >
              <Text className="f24">积分规则</Text>
              <Image className="right" mode="widthFix" src={RrightImg} />
            </View>
            <View
              className="list"
              onClick={() => {
                Taro.navigateTo({
                  url: '/pages/package-A/customer/user/points-order-list/index',
                });
              }}
            >
              <Text className="f24">兑换记录</Text>
              <Image className="right" mode="widthFix" src={RrightImg} />
            </View>
          </View>
        </View>
        {/* 2023/10/23 产品要求不清零，暂时隐藏公告 */}
        {/* {pointsExpireMonth && pointsExpireDay && (
          <View className="notice-box">
            <Image className="notice-img" mode="widthFix" src={noticeImg} />
            <Text className="notice-text">
              积分将于{pointsExpireMonth}月{pointsExpireDay}日自动清零，记得使用哦～
            </Text>
          </View>
        )} */}
        <View className="pageContentMain">
          <View className="main-top">
            <View>
              <Text className="p24">
                已连签<Text className="red">{continuousDays}</Text>天，中断将重置
              </Text>
            </View>
            {!signFlag ? (
              <View
                className="btn-box-a"
                onClick={() => {
                  action.sign(); //签到
                }}
              >
                签到
              </View>
            ) : (
              <View className="btn-box">已签</View>
            )}
          </View>
          <View className="List">
            {daysNumArr.map((item, index) => (
              <View className={item.signType ? 'itemCheck' : 'item'}>
                <Text className={item.signType ? 'dayCheck' : 'day'}>{index + 1 + '天'}</Text>
                <View
                  className={item.signType ? 'signPoints-a' : 'signPoints'}
                  style={{
                    backgroundImage: `url(${
                      item.signType
                        ? 'https://ruizhizone-test.oss-cn-nanjing.aliyuncs.com/assets/image/pointCheck/points-a.png'
                        : 'https://ruizhizone-test.oss-cn-nanjing.aliyuncs.com/assets/image/pointCheck/points.png'
                    })`,
                  }}
                >
                  {item.signPoints}
                </View>
                <Text className={item.signType ? 'pointCheck' : 'point'}>
                  {item.signType ? '已领' : '+' + item.signPoints}
                </Text>
              </View>
            ))}
          </View>
        </View>
        <View className="banner-box">
          <View
            className="left"
            onClick={() => {
              Taro.navigateTo({
                url: '/pages/package-A/taskCenter/index',
              });
            }}
          >
            <View className="topFirst">赚积分</View>
            <View className="bottom">做任务得奖励</View>
          </View>
          <View className="center"></View>
          <View
            className="right"
            onClick={() => {
              const query = Taro.createSelectorQuery();
              query
                .select('#pointsScroll')
                .node()
                .exec((res) => {
                  const scrollView = res[0].node;
                  scrollView.scrollTo({
                    top: 440,
                    animated: true,
                    duration: 1200,
                  });
                });
            }}
          >
            <View className="topFirst">花积分</View>
            <View className="bottom">精彩好礼等你来兑</View>
          </View>
        </View>
        <Tab />
        <AtCurtain
          isOpened={showMode}
          onClose={() => {
            action.commonChange('main.showMode', false);
          }}
        >
          <View className="successBox">
            <View>
              <Text className="title">已连续签到{continuousDays}天</Text>
              <Text className="content">{successMessage}</Text>
            </View>
            {giftType != 0 && (
              <Image
                className="btnIcon"
                mode="widthFix"
                src={btnImg}
                onClick={() => {
                  this.btnClick(giftType);
                }}
              />
            )}
          </View>
        </AtCurtain>
        <AdvModal
          imgUrl={this.state.imgUrl}
          handleUrl={() => handleUrl(this.state.jumpPage)}
          handleClose={() => this.handleClose()}
          isModalFlag={this.state.isModalFlag}
        />
      </ScrollView>
    );
  }
}
